package com.yoomiito.app.utils

import android.app.Activity
import android.content.Context
import android.text.TextUtils
import cn.droidlover.xdroidmvp.cache.SharedPref
import cn.droidlover.xdroidmvp.net.ApiException
import cn.droidlover.xdroidmvp.net.ApiSubscriber
import cn.droidlover.xdroidmvp.net.XApi
import com.chuanglan.shanyan_sdk.OneKeyLoginManager
import com.umeng.socialize.bean.SHARE_MEDIA
import com.yoomiito.app.Constant
import com.yoomiito.app.base.App
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.model.bean.UserInfo
import com.yoomiito.app.net.YmApi
import com.yoomiito.app.showToast
import com.yoomiito.app.ui.account.BindingPhoneActivity
import com.yoomiito.app.ui.account.InvitationCodeActivity
import com.yoomiito.app.ui.account.LoginActivity
import com.yoomiito.app.ui.push.UMManager.delAlias
import com.yoomiito.app.utils.video.VideoUtils.Companion.removePlayRecord
import com.yoomiito.app.utils.wx.WXUtils
import com.yoomiito.app.utils.wx.WXUtils.OnAuthorizationListener
import com.yoomiito.app.widget.dialog.LoadDialog
import org.greenrobot.eventbus.EventBus

object LoginUtils {

    /**
     * 闪验一键登录
     */
    fun toOneKeyLogin(context: Context) {
        if (ShanYanUtils.isInitShanYan && ShanYanUtils.isGetPhoneInfo) {
            ShanYanUtils.openLoginAuth(context) { result, token ->
                if (result) {
                    L.i("闪验登录结果Token: $token")
                    getPhoneFromShanYan(context, token)
                } else {
                    OneKeyLoginManager.getInstance().finishAuthActivity()
                    toLogin(context)
                }
            }
        } else {
            toLogin(context)
        }
    }

    /**
     * 普通登录
     */
    fun toLogin(context: Context) {
        LoginActivity.start(context)
    }

    private fun getPhoneFromShanYan(context: Context, token: String) {
//        OneKeyLoginManager.getInstance().lo
        YmApi.getYmService()
                .getPhoneFromShanYan(token, "1")
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(object : ApiSubscriber<UserInfo>() {
                    override fun onSuccess(t: UserInfo?) {
                        loginHandle(context, t)
                    }

                    override fun onFail(error: ApiException?) {
                        "验证超时 请输入手机号码".showToast()
                        toLogin(context)
                        OneKeyLoginManager.getInstance().finishAuthActivity()
                    }

                })
    }

    fun loginOut() {
        delAlias(UserInfoConfig.getUserId().toString()) //删除友盟别名
        SharedPref.getInstance(App.getInstance()).putBoolean(Constant.IS_LOGIN, false)
        SharedPref.getInstance(App.getInstance()).remove(Constant.TOKEN)
        SharedPref.getInstance(App.getInstance()).remove(Constant.UserInfo)
        SharedPref.getInstance(App.getInstance()).remove(Constant.CompanyId)
        SharedPref.getInstance(App.getInstance()).remove(Constant.RelationId)
        SharedPref.getInstance(App.getInstance()).remove(Constant.RoleId)
        SharedPref.getInstance(App.getInstance()).remove(Constant.INVITE_CODE)
        removePlayRecord() //清除播放记录
        App.mAppConfig.mCurrentUser.mUserInfo = null
        val eventMessage = EventMessage()
        eventMessage.eventType = Type.EventMsgType.LoginOut
        EventBus.getDefault().post(eventMessage)
    }

    fun WXLogin(context: Activity, share_media: SHARE_MEDIA) {
        WXUtils.wxAuthorization(context, share_media, object : OnAuthorizationListener {
            override fun onResult(access_token: String?, refresh_token: String?, openid: String?, unionid: String?) {
                val loading = LoadDialog(context)
                loading.show()
                YmApi.getYmService().verificationUser(access_token, refresh_token, openid, unionid)
                        .compose(XApi.getApiTransformerData())
                        .compose(XApi.getScheduler())
                        .subscribe(object : ApiSubscriber<UserInfo?>() {
                            override fun onSuccess(userInfo: UserInfo?) {
                                if (userInfo != null && !TextUtils.isEmpty(userInfo.token)) {
                                    SharedPref.getInstance(App.getInstance()).putString(Constant.TOKEN, userInfo.token)
                                }
                                if (userInfo == null || TextUtils.isEmpty(userInfo.id.toString() + "") || TextUtils.isEmpty(userInfo.mobile)) {
                                    BindingPhoneActivity.start(context)
                                } else if (TextUtils.isEmpty(userInfo.parent_invitation_code)) {
                                    InvitationCodeActivity.start(context,userInfo.mobile,userInfo.binding)
                                } else {
                                   loginHandle(context,userInfo)
                                }
                                if (loading.isShowing) loading.dismiss()
                            } //577085

                            override fun onFail(error: ApiException) { //201  跳转绑定邀请人
                                if (loading.isShowing) loading.dismiss()
                                L.i("error ：" + "||code:" + error.code + "||msg:" + error.msg)
                                error.msg.showToast()
                                //
                            }
                        })
            }
        })
    }

    /**
     * 登录后 初始化用户信息
     */
    fun loginHandle(context: Context, userInf: UserInfo?) {
        UserInfoConfig.putToken(userInf?.token)
        YmApi.getYmService()
                .userInfo
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(object : ApiSubscriber<UserInfo?>() {
                    override fun onSuccess(userInfo: UserInfo?) {
                        L.i("获取到用户信息")
                        UserInfoConfig.putToken(userInfo?.token)
                        when {
                            userInfo == null || TextUtils.isEmpty(userInfo.id.toString()) || TextUtils.isEmpty(userInfo.mobile) -> {
                                L.i("获取到用户信息：需要绑定手机号")
                                BindingPhoneActivity.start(context)
                            }
                            TextUtils.isEmpty(userInfo.invitation_code) -> {
                                //需要绑定邀请码 保存Token
                                L.i("获取到用户信息：需要绑定邀请码")
                                InvitationCodeActivity.start(context,userInfo.mobile,userInfo.binding)
                            }
                            else -> {
                                //去主页
                                L.i("获取到用户信息：登录成功")
                                UserInfoConfig.loginPutUserConfig(userInfo, true)
                                val em = EventMessage()
                                em.eventType = AllCode.LoginSuccess
                                EventBus.getDefault().post(em)

                            }
                        }
                        OneKeyLoginManager.getInstance().finishAuthActivity()
                    } //577085

                    override fun onFail(error: ApiException) { //201  跳转绑定邀请人
                        L.i("error ：" + "||code:" + error.code + "||msg:" + error.msg)
                        error.msg.showToast()
                        //
                    }
                })
    }
}